<html>
<head>
    <meta charset="utf-8"/>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>

<title>使用org.json创建/解析json格式文件 | 絷缘的博客</title>

<link rel="shortcut icon" href="https://zydnc.gitee.io/favicon.ico?v=1732378515642">

<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://zydnc.gitee.io/styles/main.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css">

<script src="https://cdn.jsdelivr.net/npm/@highlightjs/cdn-assets/highlight.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dockerfile.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dart.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/moment@2.27.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
<!-- DEMO JS -->
<!--<script src="media/scripts/index.js"></script>-->



    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.css">
 <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
</head>
<body>
<div class="main gt-bg-theme-color-first">
    <nav class="navbar navbar-expand-lg">
    <div class="navbar-brand">
        <img class="user-avatar" src="/images/avatar.png" alt="头像">
        <div class="site-name gt-c-content-color-first">
            絷缘的博客
        </div>
    </div>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <i class="fas fa-bars gt-c-content-color-first" style="font-size: 18px"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <div class="navbar-nav mr-auto" style="text-align: center">
            
                <div class="nav-item">
                    
                        <a href="/" class="menu gt-a-link">
                            首页
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/archives" class="menu gt-a-link">
                            归档
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/tags" class="menu gt-a-link">
                            标签
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/about" class="menu gt-a-link">
                            关于
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/friends" class="menu gt-a-link">
                            友链
                        </a>
                    
                </div>
            
        </div>
        <div style="text-align: center">
            <form id="gridea-search-form" style="position: relative" data-update="1732378515642" action="/search/index.html">
                <input class="search-input" autocomplete="off" spellcheck="false" name="q" placeholder="搜索文章" />
                <i class="fas fa-search gt-c-content-color-first" style="position: absolute; top: 9px; left: 10px;"></i>
            </form>
        </div>
    </div>
</nav>

    <div class="post-container">
        <div class="post-detail gt-bg-theme-color-second">
            <article class="gt-post-content">
                <h2 class="post-title">
                    使用org.json创建/解析json格式文件
                </h2>
                <div class="post-info">
                    <time class="post-time gt-c-content-color-first">
                        · 2021-01-03 ·
                    </time>
                    
                        <a href="https://zydnc.gitee.io/EU-phZhGZ/" class="post-tags">
                            # JSON
                        </a>
                    
                        <a href="https://zydnc.gitee.io/i5GlEtKUCf/" class="post-tags">
                            # org.json
                        </a>
                    
                        <a href="https://zydnc.gitee.io/java/" class="post-tags">
                            # Java
                        </a>
                    
                </div>
                <div class="post-content">
                    <blockquote>
<p>本教程仅限于  <code>org.jsonv20201115</code> + <code>jdk1.8</code></p>
</blockquote>
<h2 id="一-在pomxml中加入orgjson的依赖文件">一、在pom.xml中加入org.json的依赖文件</h2>
<pre><code class="language-xml">&lt;!-- https://mvnrepository.com/artifact/org.json/json --&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.json&lt;/groupId&gt;
    &lt;artifactId&gt;json&lt;/artifactId&gt;
    &lt;version&gt;20201115&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h2 id="二-书写代码使用无参构造创建json格式文本">二、书写代码，使用无参构造创建Json格式文本</h2>
<pre><code class="language-java">public static String createJsonText(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(&quot;name&quot;,&quot;絷缘&quot;);
        jsonObject.put(&quot;age&quot;,23);
        jsonObject.put(&quot;gender&quot;,&quot;male&quot;);
        jsonObject.put(&quot;now_time&quot;,new SimpleDateFormat(&quot;yyyy-MM-dd kk:mm:ss&quot;).format(new Date(System.currentTimeMillis())));
        jsonObject.put(&quot;skills&quot;,new String[]{&quot;Java&quot;,&quot;Linux&quot;,&quot;JavaScript&quot;,&quot;Vue&quot;,&quot;SemanticUI&quot;,&quot;NodeJS&quot;});
        jsonObject.put(&quot;has_house&quot;,false);
        jsonObject.put(&quot;has_car&quot;,false);
        return jsonObject.toString();
}
</code></pre>
<h2 id="三-书写代码使用有参构造传入hashmap对象创建json格式文本">三、书写代码，使用有参构造传入HashMap对象创建Json格式文本</h2>
<pre><code class="language-java">public static String createJsonByMap(){
        HashMap&lt;String, Object&gt; hashMap = new HashMap&lt;String, Object&gt;();
        hashMap.put(&quot;name&quot;,&quot;絷缘&quot;);
        hashMap.put(&quot;age&quot;,23);
        hashMap.put(&quot;gender&quot;,&quot;male&quot;);
        hashMap.put(&quot;now_time&quot;,new SimpleDateFormat(&quot;yyyy-MM-dd kk:mm:ss&quot;).format(new Date(System.currentTimeMillis())));
        hashMap.put(&quot;skills&quot;,new String[]{&quot;Java&quot;,&quot;Linux&quot;,&quot;JavaScript&quot;,&quot;Vue&quot;,&quot;SemanticUI&quot;,&quot;NodeJS&quot;});
        hashMap.put(&quot;has_house&quot;,false);
        hashMap.put(&quot;has_car&quot;,false);
        JSONObject jsonObject = new JSONObject(hashMap);
        return jsonObject.toString();
    }
</code></pre>
<h2 id="四-书写代码封装javabean实现创建json格式文本">四、书写代码，封装JavaBean实现创建Json格式文本</h2>
<pre><code class="language-java">import java.util.Arrays;

public class Person {
    private String name;
    private int age;
    private String gender;
    private boolean has_house;
    private boolean has_car;
    private String [] skills;
    public Person(){}
    public Person(String name, int age, String gender, boolean has_house, boolean has_car, String[] skills) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.has_house = has_house;
        this.has_car = has_car;
        this.skills = skills;
    }
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getGender() {
        return gender;
    }

    public boolean isHas_house() {
        return has_house;
    }

    public boolean isHas_car() {
        return has_car;
    }

    public String[] getSkills() {
        return skills;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setHas_house(boolean has_house) {
        this.has_house = has_house;
    }

    public void setHas_car(boolean has_car) {
        this.has_car = has_car;
    }

    public void setSkills(String[] skills) {
        this.skills = skills;
    }
}
</code></pre>
<pre><code class="language-java">public static String createJsonByBean(){
        Person person = new Person(&quot;絷缘&quot;, 23, &quot;male&quot;, false, false, new String[]{&quot;Java&quot;, &quot;Linux&quot;, &quot;JavaScript&quot;, &quot;Vue&quot;, &quot;SemanticUI&quot;, &quot;NodeJS&quot;});
        JSONObject jsonObject = new JSONObject(person);
        return jsonObject.toString();
    }
</code></pre>
<h2 id="书写代码实现解析json文本">书写代码，实现解析Json文本</h2>
<p><code>需要自己创建文件person.json置于src目录（普通项目）或resources目录下（Maven项目）</code></p>
<pre><code class="language-json">{
  &quot;skills&quot;: [
    &quot;Java&quot;,
    &quot;Linux&quot;,
    &quot;JavaScript&quot;,
    &quot;Vue&quot;,
    &quot;SemanticUI&quot;,
    &quot;NodeJS&quot;
  ],
  &quot;has_car&quot;: false,
  &quot;gender&quot;: &quot;male&quot;,
  &quot;name&quot;: &quot;絷缘&quot;,
  &quot;has_house&quot;: false,
  &quot;age&quot;: 23
}
</code></pre>
<p><code>为了方便看代码，文章中出现的异常我都会抛出</code></p>
<pre><code class="language-java">public static void parseJson() throws IOException {
        InputStream is = JsonDemo1.class.getClassLoader().getResourceAsStream(&quot;person.json&quot;);
        BufferedReader br = new BufferedReader(new InputStreamReader(is, &quot;UTF-8&quot;));
        StringBuilder sb = new StringBuilder();
        String content;
        while((content=br.readLine())!=null){
            sb.append(content);
        }
        System.out.println(sb.toString());
        JSONObject jsonObject = new JSONObject(sb.toString());
        System.out.println(jsonObject.getString(&quot;name&quot;));
        System.out.println(jsonObject.getJSONArray(&quot;skills&quot;));
        System.out.println(jsonObject.getString(&quot;gender&quot;));
        System.out.println(jsonObject.getInt(&quot;age&quot;));
        System.out.println(jsonObject.getBoolean(&quot;has_house&quot;));
        System.out.println(jsonObject.getBoolean(&quot;has_car&quot;));
    }
</code></pre>
<blockquote>
<p>原文作者：絷缘<br>
作者邮箱：zhiyuanworkemail@163.com<br>
原文地址：<a href="https://zhiyuandnc.github.io/4riCXnG78/">https://zhiyuandnc.github.io/4riCXnG78/</a><br>
版权声明：本文为博主原创文章，转载请注明原文链接作者信息</p>
</blockquote>

                </div>
            </article>
        </div>

        
            <div class="next-post">
                <div class="next gt-c-content-color-first">下一篇</div>
                <a href="https://zydnc.gitee.io/-gGSoZP8v/" class="post-title gt-a-link">
                    Druid数据库连接池技术
                </a>
            </div>
        

        

        

        

        <div class="site-footer gt-c-content-color-first">
    <div class="slogan gt-c-content-color-first">事实不以人的意志为转移</div>
    <div class="social-container">
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-github gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-telegram gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-qq gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-bilibili gt-c-content-color-first"></i>
                </a>
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
    </div>
    <div class="footer-info">
        Copyright&ensp;&copy;&ensp;絷缘的博客<br/><a href="https://beian.miit.gov.cn/" target="_blank">晋ICP备20001723号-1</a>
    </div>
    <div>
        Theme by <a href="https://imhanjie.com/" target="_blank">imhanjie</a>, Powered by <a
                href="https://github.com/getgridea/gridea" target="_blank">Gridea | <a href="https://zydnc.gitee.io/atom.xml" target="_blank">RSS</a></a>
    </div>
</div>

<script>
  hljs.initHighlightingOnLoad()
</script>

    </div>
</div>
</body>
</html>
